#include "obj_obstacle.h"

int obj_obstacle::cloaded = 0;
GLuint obj_obstacle::textures[];

obj_obstacle::obj_obstacle(){
	if (cloaded==0)
		FOR (i,OBSTACLE_TYPE_NUM)
			textures[i]=-1;
}

int obj_obstacle::load (int type) {
	FILE * _file;
	char filename[100];
	sprintf(filename, "./media/objects/obj_obstacle%d",type);	
	_file = fopen(filename,"r");
	int verts_num, faces_num,UVs_num, face_verts_num;
	if(fscanf(_file,"%d", &verts_num)==EOF){debug("Unexpected End Of File");return -1;}
	if(fscanf(_file,"%d", &faces_num)==EOF){debug("Unexpected End Of File");return -1;}
	if(fscanf(_file,"%d", &UVs_num)==EOF){debug("Unexpected End Of File");return -1;}
	verts.resize(verts_num);
	faces.resize(faces_num);
	UVs.resize(UVs_num);
	for (int i=0;i<verts_num;i++)
		fscanf(_file,"%f %f %f", &verts[i][0], &verts[i][1], &verts[i][2]);
	for (int i=0;i<faces_num;i++){
		fscanf(_file,"%d", &face_verts_num);
		switch (face_verts_num){
			case 3:
				if (fscanf(_file,"%d %d %d %d %d %d", &faces[i][0], &faces[i][1], &faces[i][2], &faces[i][3], &faces[i][4], &faces[i][5])==EOF){debug("Unexpected End Of File");return -1;}
				break;
/*			case 4:
				fscanf(_file,"%d %d %d %d", &faces[i][0], &faces[i][1], &faces[i][2], &faces[i][3]);
				break;
*/			default:
				debug("Wrong number of face verticles\n");
				return -1;
				break;
		}
	}
	
	for (int i=0;i<UVs_num;i++)
		if(fscanf(_file,"%f %f", &UVs[i][0], &UVs[i][1])==EOF){debug("Unexpected End Of File");return -1;}

	if (textures[type]==(GLuint) -1){
		sprintf(filename,"%s.tga",filename);
		textures[type]=load_tga_texture(filename);
		if (textures[type]==(GLuint)-1){
			debug("Can't find right picture");
			return -1;
		}
	}
	texture=textures[type];

	z=0;
	
 	loaded=1;
	transparent=1;
	collide=1;
	calc_r();
	return 0;
}

